<template>
  <div class="page-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>我的购物车</span>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="handleBuy">购买</el-button>
          </div>
        </div>
        </template>
      <el-table
        :data="cartItems"
        style="width: 100%"
        border
        class="cart-table"
        stripe
        height="100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="productId" label="商品ID" width="120" />
        <el-table-column prop="productName" label="商品名称" min-width="200" />
        <el-table-column prop="quantity" label="数量" width="100" />
        <el-table-column prop="createTime" label="添加时间" width="180" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" type="danger" @click="handleRemove(scope.row)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @update:current-page="fetchCart"
          @update:page-size="fetchCart"
          class="pagination"
        />
        <div class="pagination-info">
          当前第 {{ currentPage }} 页，显示 {{ (currentPage - 1) * pageSize + 1 }}-{{ Math.min(currentPage * pageSize, total) }} 条，共 {{ total }} 条
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { getCartService, removeCartItemService } from '@/api/user'
import { useUserInfoStore } from '../../stores/userInfo'
import { addOrderApi } from '../../api/pay'
import { useRouter } from 'vue-router';
const router = useRouter();
const userInfoStore = useUserInfoStore()
const cartItems = ref([])
const selectedItems = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const fetchCart = async () => {
  if (!userInfoStore.userInfo?.id) {
    ElMessage.error('用户未登录')
    cartItems.value = []
    total.value = 0
    return
  }
  try {
    const res = await getCartService(currentPage.value, pageSize.value, userInfoStore.userInfo.id)
    console.log('Response:', res)
    cartItems.value = res.data.data.data || []
    total.value = res.data.data.total || 0
    // 同步选中状态
    cartItems.value.forEach(item => {
      item.selected = selectedItems.value.includes(item.id)
    })
  } catch (error) {
    console.error('Fetch cart error:', error)
    ElMessage.error('获取购物车失败')
    cartItems.value = []
    total.value = 0
  }
}

const handleSelectionChange = (val) => {
  selectedItems.value = val.map(item => item.id)
}

const handleRemove = async (row) => {
  try {
    await removeCartItemService(row.id)
    ElMessage.success('移除成功')
    fetchCart()
  } catch (error) {
    console.error('Remove cart item error:', error)
    ElMessage.error('移除失败')
  }
}

const handleBuy = async () => {
  // 1. 基础校验
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择要购买的商品');
    return;
  }

  // 2. 获取用户信息
  if (!userInfoStore.userInfo?.id) {
    ElMessage.error('请先登录');
    return router.push('/login');
  }

  try {
    // 1. 获取选中的第一个购物车项
    const selectedItem = cartItems.value.find(item => 
      selectedItems.value.includes(item.id)
    );
    
    if (!selectedItem) {
      throw new Error('未找到选中商品');
    }

    // 2. 准备请求数据（确保字段名与后端DTO完全一致）
    const requestData = {
      userId: userInfoStore.userInfo.id, // ✅ 修正变量名
      skuId: selectedItem.productId,     // ✅ 使用productId作为skuId（根据您确认）
      quantity: selectedItem.quantity    // ✅ 使用购物车中的数量
    };

    // 3. 调试日志
    console.log('最终请求数据:', JSON.stringify(requestData));

    // 4. 调用API
    const orderRes = await addOrderApi(requestData);
    console.log('这是我',orderRes)
    // 5. 处理订单创建结果
    if (orderRes.data.code !== '200') {
      throw new Error(orderRes.data?.message || '订单创建失败');
    }

    // 6. 跳转到支付选择页
    router.push({ 
      path: '/pay/choose', 
      query: { 
        orderSn: orderRes.data.data.orderSn,
        totalAmount: orderRes.data.data.totalAmount,
        productCount: orderRes.data.data.quantity// 新增传递商品数量
      }
    });

    // 7. 清除已购买的商品项（优化版）
    await Promise.all(
      selectedItems.value.map(id => 
        removeCartItemService(id).catch(e => console.error('移除购物车项失败:', e))
      )
    );
    fetchCart();

  } catch (error) {
    console.error('完整错误信息:', {
      error: error.stack,
      requestData: {
        userId: userInfoStore.userInfo?.id,
        selectedItems: selectedItems.value
      }
    });
    ElMessage.error(error.message.includes('SKU信息') 
      ? error.message 
      : (error.response?.data?.message || '购买流程出错，请稍后重试')
    );
  }
};

// const handlePrepared = async () => {
//   try {
//     const res = await axios.post('/api/cart/prepared', {}, {
//       headers: { 'User-Id': userInfoStore.userInfo.id }
//     })
//     ElMessage.success(res.data.message || '预留功能调用成功')
//   } catch (error) {
//     console.error('Prepared action error:', error)
//     ElMessage.error('预留功能调用失败')
//   }
// }

fetchCart()
</script>

<style lang="scss" scoped>
.page-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.box-card {
  margin: 0;
  padding: 16px;
  border-radius: 10px;
  box-shadow: var(--shadow);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-color);
  padding: 12px 16px;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.cart-table {
  flex: 1;
  overflow: hidden;
}

.pagination-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px 16px;
  background-color: var(--card-bg);
}

.pagination {
  margin-bottom: 10px;
}

.pagination-info {
  font-size: 14px;
  color: var(--text-color);
}
</style>